<template>
  <el-select
    v-model="bookId"
    placeholder="请选择教材"
    clearable
    filterable
    remote
    :remote-method="remoteMethod"
    no-data-text="defaultName"
    @focus="focus"
    @change="change"
    :loading="loading"
    v-loadmore="loadmore"
  >
    <el-option
      v-for="item in bookList.length>0?bookList:allBookList"
      :key="item.is"
      :label="item.name"
      :value="item.code"
    >
    </el-option>
  </el-select>
</template>
<script>
import { listBooks } from '@/api/curriculumSystemManagement/book'
export default {
  name: 'selectBook',
  props: {
    code: {
      type: Number | String,
      default: 0
    },
    defaultName:{
      type:String,
      default: ''
    }
  },
  data() {
    return {
      bookId: null,
      //学校下拉框数据
      bookList: [],
      allBookList:[],
      loadingBook: true,
      queryParames: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      bookTotal: 10,
      loading: false
    }
  },
  created() {
    this.bookId = this.code
    // this.getBookList()
  },
  watch:{
    code(newVal,oldVal){
      this.bookId = newVal
    }
  },
  methods: {
    /** 下拉框选中值发生改变*/
    change(e) {
      this.$emit('selectChange', e)
    },
    /** 下拉框搜索*/
    async remoteMethod(query) {
      const self = this
      self.queryParames.name = query
      self.loading = true
      self.bookList = []
      self.queryParames.pageNum = 1
      await self.getBookList()
      self.loading = false
    },
    /** 下拉框触底*/
    loadmore() {
      const self = this
      if (self.loadingBook) {
        self.queryParames.pageNum++
        self.getBookList()
      }
    },
    /** 下拉框获取焦点时*/
    async focus () {
      const self = this
      self.loading = true
      self.bookList = []
      self.queryParames.pageNum = 1
      self.queryParames.name = ''
      self.bookTotal = 10
      await self.getBookList()
      self.loading = false
    },
    /** 获取学校下拉框数据*/
    async getBookList() {
      const self = this
      if (self.bookList.length >= self.bookTotal) {
        self.loadingBook = false
        return
      }
      const response = await listBooks(self.queryParames)
      self.bookList = self.bookList.concat(response.rows)
      self.bookTotal = response.total
    },

    /** 获取所有的教材数据*/
    async getAllBookList(){
      const self = this
      let query = {
        pageNum: 1,
        pageSize: 1000,
      }
      const response = await listBooks(query)
      self.allBookList = response.rows
    }
  }
}
</script>
<style scoped lang="scss">

</style>
